一峰说:Mybatis | 您所在的位置:网站首页 › mybatisplus limit多了一个 › 一峰说:Mybatis |
以下是本人学习的观点,如果有错或者说得不全面,记得告诉我哟
Mybatis-Plus是什么
是一个方便的操作数据库功能的代码工具。有一个叫mybatis的技术框架因为经常要自己配置各种文件,进行很多次重复操作,使得常常会不小心出错,这时把经常重复的东西直接封装起来,甚至可以设置属性生成代码能让工作量减少很多,就在原来mybatis基础上整合诞生了一个工具,叫mybatis-plus。
因为我们配置都是已经封装好的,所以我们需要知道是怎么运作的,就需要生成日志来看看。 #配置日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl把@TableId(type = IdType.AUTO)放在ID声明上面 @TableId(type = IdType.AUTO) private Long id;数据库字段一定要自增! int result = userMapper.insert(user); // 因为在对象ID上添加了注释(),MP会帮我们自动生成id, System.out.println(result); // 受影响的行数 System.out.println(user); // 发现,id会自动回填 读单一查询: userMapper.selectById(id);批量查询: List users = userMapper.selectBatchIds(Arrays.asList(id1, id2, id3)); users.forEach(System.out::println);分页查询: 1、在配置类里面加上配置拦截器组件,一般配置类是config @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } 2.直接使用Page对象 Page page = new Page(当前页,页面大小); userMapper.selectPage(page,null); page.getRecords().forEach(System.out::println); 更乐观锁(乐观就是认为一切都是乐观,无论干什么都不会去想太多,就不去上锁,如果出现了问题再次更新值测试): 比如:一个人带了10快去买菜,突然一个人插队把10块把东西买走了,老板看这么好抢手就直接坐地起价表明20块才能买,结果第一个人带的钱不够,就买不到菜了。 @Version private Integer version; // 注册乐观锁插件 @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } //用乐观锁测试成功 @Test public void testOptimisticLocker(){ //1.查询用户信息 User user=userMapper.selectById(1L); //2.修改用户信息 user.setName("fever"); user.setEmail("[email protected]"); userMapper.updateById(user); } //用乐观锁测试失败! @Test public void testOptimisticLocker2(){ //线程1 User user=userMapper.selectById(1L); user.setName("fever111"); user.setEmail("9**********[email protected]"); //模拟另一个线程执行了插队操作 User user2=userMapper.selectById(1L); user.setName("fever222"); user.setEmail("9**********[email protected]"); userMapper.updateById(user2); //结果是执行了上面的user2的语句 userMapper.updateById(user);//如果没有乐观锁,会把上面user2覆盖了 }悲观锁(悲观就是认为它总是会出现问题,无论干什么都要上锁,再去操作) 时间: 一般更新会有创建时间和修改时间! // 字段添加填充内容 @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; 配置: @Component // 一定不要忘记把处理器加到IOC容器中! public class MyMetaObjectHandler implements MetaObjectHandler { // 插入时的填充策略 @Override public void insertFill(MetaObject metaObject) { log.info("start insert fill....."); // setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject this.setFieldValByName("createTime",new Date(),metaObject); this.setFieldValByName("updateTime",new Date(),metaObject); } // 更新时的填充策略 @Override public void updateFill(MetaObject metaObject) { log.info("start update fill....."); this.setFieldValByName("updateTime",new Date(),metaObject); } } 删物理删除:直接从数据库中直接移除 //测试删除 userMapper.deleteById(id); //id批量删除 userMapper.deleteBatchIds(Arrays.asList(id1,id2));逻辑删除:再数据库中没有被移除,而是通过一个变量来让它失效!deleted=0 => deleted=1 @TableLogic //逻辑删除 private Integer deleted; //在配置类上加上这个bean组件 @Bean public ISqlInjector sqlInjector() { return new LogicSqlInjector(); } 在application.properties中添加: # 配置逻辑删除 mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0测试后会发现,执行删除功能是更新操作,把deleted的值从0更新到1 性能分析插件MP有一个性能拦截器,可以控制sql语句的执行,一般用来判断sql语句的执行时间,如果超过一定的时间就不需要再执行。 1.导入插件 /** * SQL执行效率插件 */ @Bean @Profile({"dev","test"})// 设置 dev test 环境开启,保证我们的效率 public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(100); // ms设置sql执行的最大时间,如果超过了则不执行 performanceInterceptor.setFormat(true); // 是否格式化代码 return performanceInterceptor; } PS:要在SpringBoot中配置环境为dev或者 test 环境! 项目中涉及应用配置的相关配置文件比较多,应用程序在不同的环境可能会有不同的配置,例如数据库连接、日志级别等,开发,测试,生产每个环境可能配置都不一致,这将会给系统运维带来诸多的麻烦。 条件构造器一些复杂的sql语句功能可以在测试代码用wrapper来封装,再进行查询 @Test void contextLoads() { //查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12 QueryWrapper wrapper=new QueryWrapper(); wrapper.isNotNull("name").isNotNull("email").ge("age",12); userMapper.selectList(wrapper).forEach(System.out::println);就是可以通过写好程序运行就能生产我们后台的所有原本要自己写的dao.pojo,service,controller等,极大提高了开发效率。 import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.po.TableFill; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import java.util.ArrayList; // 代码自动生成器 public class FeverCode { public static void main(String[] args) { // 需要构建一个 代码自动生成器 对象 AutoGenerator mpg = new AutoGenerator(); // 配置策略 // 1、全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir");//获取用户程序当前路径(项目根的路径) gc.setOutputDir(projectPath+"/src/main/java");//生成文件的输出目录 gc.setAuthor("一峰");//开发人员 gc.setOpen(false);//是否打开输出目录 gc.setFileOverride(false); // 是否覆盖已有文件(默认值:false) gc.setServiceName("%sService"); // 去Service的I前缀 gc.setIdType(IdType.ID_WORKER);//主键策略(查看是否为string或long) gc.setDateType(DateType.ONLY_DATE);定义生成的实体类中日期类型 gc.setSwagger2(true);//是否生成swagger2文档 mpg.setGlobalConfig(gc);//把全局配置添加到代码生成器主类 //2、设置数据源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/*****? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver");//低版本mysql是com.mysql.jdbc.Driver dsc.setUsername("root"); dsc.setPassword("123456"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc);//把数据源配置添加到代码生成器主类 //3、包的配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("blog"); pc.setParent("com.kuang");//模块名 pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setController("controller"); mpg.setPackageInfo(pc); //4、策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("blog_tags","course","links","sys_settings","user_record"," user_say"); // 设置要映射的表名 strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略 strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略 strategy.setEntityLombokModel(true); // 自动lombok; strategy.setLogicDeleteFieldName("deleted");//开启逻辑删除 // 自动填充配置 TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);//自动增加时间 TableFill gmtModified = new TableFill("gmt_modified",//自动修改时间 FieldFill.INSERT_UPDATE); ArrayList tableFills = new ArrayList(); tableFills.add(gmtCreate); tableFills.add(gmtModified); strategy.setTableFillList(tableFills); // 乐观锁 strategy.setVersionFieldName("version"); strategy.setRestControllerStyle(true);//restful api风格控制器 strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符 mpg.setStrategy(strategy);//把设置好的策略添加到主类 mpg.execute(); //执行 } } |
CopyRight 2018-2019 实验室设备网 版权所有 |